package cn.edu.zime.tjh.iotapp;

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.google.android.material.floatingactionbutton.FloatingActionButton;

import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import cn.edu.zime.tjh.iotapp.api.ApiCallback;
import cn.edu.zime.tjh.iotapp.api.ApiClient;
import cn.edu.zime.tjh.iotapp.api.ApiService;

public class ServerStatusActivity extends AppCompatActivity {

    private static final String TAG = "ServerStatusActivity";
    
    // UI组件
    private ImageView imageStatusIndicator;
    private TextView textStatus;
    private TextView textResponseTime;
    private TextView textLastCheck;
    private TextView textServerAddress;
    private FloatingActionButton fabRefresh;
    
    // API服务
    private ApiService apiService;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_server_status);
        
        // 初始化API服务
        apiService = ApiService.getInstance();
        
        // 初始化UI组件
        initViews();
        
        // 设置刷新按钮
        fabRefresh.setOnClickListener(v -> checkServerStatus());
        
        // 初始检查服务器状态
        checkServerStatus();
    }
    
    private void initViews() {
        imageStatusIndicator = findViewById(R.id.imageStatusIndicator);
        textStatus = findViewById(R.id.textStatus);
        textResponseTime = findViewById(R.id.textResponseTime);
        textLastCheck = findViewById(R.id.textLastCheck);
        textServerAddress = findViewById(R.id.textServerAddress);
        fabRefresh = findViewById(R.id.fabRefresh);
        
        // 设置初始服务器信息
        textServerAddress.setText(ApiClient.getInstance().getBaseUrl());
        
        // 设置标题
        TextView titleText = null;
        if (titleText != null) {
            titleText.setText("服务器状态");
        }
    }
    
    private void checkServerStatus() {
        // 显示检测中状态
        updateStatus("检测中...", getResources().getColor(R.color.status_unknown));
        imageStatusIndicator.setImageResource(R.drawable.ic_status_unknown);
        textResponseTime.setText("--");
        
        // 记录开始时间
        long startTime = System.currentTimeMillis();
        
        // 测试服务器连接
        apiService.testConnection(new ApiCallback() {
            @Override
            public void onSuccess(JSONObject response) {
                // 计算响应时间
                long responseTime = System.currentTimeMillis() - startTime;
                
                // 更新状态为在线
                updateStatus("在线", getResources().getColor(R.color.status_online));
                imageStatusIndicator.setImageResource(R.drawable.ic_status_online);
                
                // 更新响应时间
                updateResponseTime(responseTime);
                
                // 更新最后检查时间
                updateLastCheckTime();
                
                Toast.makeText(ServerStatusActivity.this, "服务器在线", Toast.LENGTH_SHORT).show();
            }
            
            @Override
            public void onFailure(String errorMessage) {
                // 计算响应时间(如果有)
                long responseTime = System.currentTimeMillis() - startTime;
                
                // 更新状态为离线
                updateStatus("离线", getResources().getColor(R.color.status_offline));
                imageStatusIndicator.setImageResource(R.drawable.ic_status_offline);
                
                // 如果是超时，显示超时信息
                if (errorMessage.contains("timed out") || errorMessage.contains("timeout")) {
                    updateResponseTime(responseTime);
                } else {
                    textResponseTime.setText("--");
                }
                
                // 更新最后检查时间
                updateLastCheckTime();
                
                Toast.makeText(ServerStatusActivity.this, "无法连接到服务器", Toast.LENGTH_SHORT).show();
            }
        });
    }
    
    private void updateStatus(String status, int color) {
        runOnUiThread(() -> {
            textStatus.setText(status);
            textStatus.setTextColor(color);
        });
    }
    
    private void updateResponseTime(long responseTime) {
        runOnUiThread(() -> {
            textResponseTime.setText(responseTime + " ms");
        });
    }
    
    private void updateLastCheckTime() {
        runOnUiThread(() -> {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
            String currentTime = sdf.format(new Date());
            textLastCheck.setText(currentTime);
        });
    }
    
    // 返回按钮点击事件
    public void back(View view) {
        finish();
    }
} 